class Topic < ActiveRecord::Base
  belongs_to :user, :counter_cache => true
  belongs_to :forum, :counter_cache => true
  has_many :comments,:foreign_key=>"obj_id", :conditions=>"category_id=4"
  
  def before_create
    self.view_times=0
    self.reply_times=0
    self.created_at= Time.now
    self.updated_at= Time.now
    self.search_tag= self.title
  end
  
  def after_create
    Index.index_search_tag(self)
  end
  
  def before_destroy
    Comment.destroy_all(["category_id=4 and obj_id=?",self.id])
 #  Statistic.destroy_all(["category_id=4 and obj_id=?",self.id])
  end
  
  def after_destory
    forum.deletetopic(user_id) 
  end
  
  def add_reply(reply)
    self.update_topic(reply.user)
    self.reply_times+=1
    self.save
  end
  
  def update_topic(user)
    self.updated_at=Time.now
    self.last_user_id=user.id
    self.save
  end
  
  def reindex_search_tag
    self.search_tag= self.title
    Index.clear_search_tag(self)
    Index.index_search_tag(self)
  end
  
  def self.validate_params(params)
    if params[:title]==nil || (params[:title].length>30 || params[:title]=="")
      return ["<li>对不起，您的标题过长或者为空！</li>"]
    elsif params[:body]=="" || params[:body]==nil
      return ["<li>对不起，您的话题内容不能为空！</li>"]
    else
      return []
    end
  end
  
end
